<template>
  <div class="props-child">
    <h4 class="font-medium text-gray-800 mb-3">子组件接收到的 Props：</h4>

    <!-- 显示接收到的数据 -->
    <div class="space-y-3">
      <div class="prop-item">
        <span class="prop-label">消息:</span>
        <span class="prop-value">{{ message }}</span>
      </div>

      <div class="prop-item">
        <span class="prop-label">计数:</span>
        <span class="prop-value">{{ count }}</span>
        <div class="mt-2">
          <button
            @click="requestCountUpdate"
            class="text-sm px-3 py-1 bg-blue-500 text-white rounded hover:bg-blue-600"
          >
            请求父组件更新计数 (+5)
          </button>
        </div>
      </div>

      <div class="prop-item">
        <span class="prop-label">状态:</span>
        <span :class="isActive ? 'text-green-600' : 'text-red-600'" class="prop-value">
          {{ isActive ? '激活' : '未激活' }}
        </span>
      </div>

      <div class="prop-item">
        <span class="prop-label">用户信息:</span>
        <div class="prop-value">
          <div class="text-sm space-y-1">
            <p>姓名: {{ userInfo.name }}</p>
            <p>年龄: {{ userInfo.age }}</p>
            <p>技能: {{ userInfo.skills.join(', ') }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 演示单向数据流 -->
    <div class="mt-4 p-3 bg-yellow-50 border border-yellow-200 rounded">
      <h5 class="text-sm font-medium text-yellow-800 mb-2">🚫 单向数据流演示</h5>
      <p class="text-xs text-yellow-700 mb-2">子组件不能直接修改 props，以下按钮会抛出警告:</p>
      <button
        @click="tryToModifyProp"
        class="text-xs px-2 py-1 bg-yellow-500 text-white rounded hover:bg-yellow-600"
      >
        尝试直接修改 props (错误做法)
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { defineProps, defineEmits } from 'vue'

// Props 类型定义和验证
interface UserInfo {
  name: string
  age: number
  skills: string[]
}

interface Props {
  message: string
  count: number
  isActive: boolean
  userInfo: UserInfo
}

// 定义 props 和默认值
const props = withDefaults(defineProps<Props>(), {
  message: '默认消息',
  count: 0,
  isActive: false,
  userInfo: () => ({
    name: '默认用户',
    age: 0,
    skills: [],
  }),
})

// 定义 emits
const emit = defineEmits<{
  updateCount: [count: number]
}>()

// 正确的做法：通过 emit 请求父组件更新数据
const requestCountUpdate = () => {
  emit('updateCount', props.count + 5)
}

// 错误的做法：尝试直接修改 props（仅用于演示）
const tryToModifyProp = () => {
  try {
    // 这会产生 Vue 警告，但不会真正修改数据
    ;(props as any).message = '尝试修改的消息'
    console.warn('这是错误的做法！Vue 会阻止这种操作。')
  } catch (error) {
    console.error('无法直接修改 props:', error)
  }
}
</script>

<style scoped lang="scss">
.props-child {
  @apply border border-gray-200 rounded-lg p-4 bg-gray-50;
}

.prop-item {
  @apply flex flex-col space-y-1;
}

.prop-label {
  @apply text-sm font-medium text-gray-600;
}

.prop-value {
  @apply text-sm text-gray-800 bg-white px-2 py-1 rounded border;
}
</style>
